package rjeutsky.database.jpa;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import rjeutsky.database.jpa.models.JPAUserRole;
import rjeutsky.models.UserRole;

public class JPAUserRoleRepository extends BaseCRUDDomainRepository<UserRole>{

	public JPAUserRoleRepository(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public List<UserRole> query() throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<UserRole> roles =  JPAUserRole.getUserRoles(session.createQuery("From JPAUserRole").list());
		
		session.getTransaction().commit();
		session.close();
		
		return roles;
	}

	@Override
	public void create(UserRole item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUserRole role = new JPAUserRole();
		role.setName(item.getName());
		session.save(role);
		item.setId(role.getId());
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public UserRole read(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		UserRole userRole = null;
		
		JPAUserRole jpaUserRole = (JPAUserRole) session.get(JPAUserRole.class, id);
		if (jpaUserRole != null) {
			userRole = jpaUserRole.getUserRole();
		}
		
		session.getTransaction().commit();
		session.close();
		return userRole;
	}

	@Override
	public void update(UserRole item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUserRole userRole = JPAUserRole.getJPAUserRole(session, item);
		if (userRole != null) {
			userRole.setName(item.getName());
		}
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void delete(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAUserRole userRole = (JPAUserRole) session.get(JPAUserRole.class, id);
		if (userRole != null) {
			session.delete(userRole);
		}
		
		session.getTransaction().commit();
		session.close();
	}

}
